package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.dto.IndexDataDto;
import com.zzyl.nursing.dto.MemberUserAddDto;
import com.zzyl.nursing.dto.UserLoginDto;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.ElderDetailVO;
import com.zzyl.nursing.vo.FamilyElderVO;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.FamilyMemberElderVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.PropertyStatusInfoVO;
import com.zzyl.nursing.vo.PageListVo;
import com.zzyl.nursing.vo.PropertyStatusInfoVO;
import com.zzyl.nursing.vo.health.IndexDataVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-22
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private IFamilyMemberElderService familyMemberElderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IDeviceService deviceService;




    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private WechatService wechatService;

    private List<String> nickNameList = Arrays.asList("好柿开花", "大吉大利", "今晚吃鸡", "三羊开泰");

    @Autowired
    private TokenService tokenService;

    /**
     * 微信小程序登录接口
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginDto dto) {
        //1. 获取微信唯一身份标识openId
        String openId = wechatService.getOpenId(dto.getCode());

        //2. 根据openId查询用户
        FamilyMember member = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();

        //3. 如果用户不存在则新增用户（自动注册）
        if(member==null) {
            Collections.shuffle(nickNameList);//打乱集合中元素的顺序

            //生成随机昵称
            String nickName  = nickNameList.get(0) + RandomStringUtils.randomNumeric(4);

            member = FamilyMember.builder()
                    .openId(openId) //唯一标识
                    .name(nickName)//昵称
                    .build();
            this.save(member);
        }

        //4. 如果手机号不存在则获取微信绑定的手机号
        if(StrUtil.isBlank(member.getPhone())) {
            String phoneNum = wechatService.getPhoneNum(dto.getPhoneCode());

            //5. 更新手机号到用户表
//            FamilyMember memberUpdate = FamilyMember.builder()
//                    .id(member.getId()) //更新条件
//                    .phone(phoneNum)//更新字段对应的值
//                    .build();
//            this.updateById(memberUpdate);

            if(StrUtil.isNotBlank(phoneNum)) {
                this.lambdaUpdate()
                        .eq(FamilyMember::getId, member.getId()) //更新条件
                        .set(FamilyMember::getPhone, phoneNum)//更新字段对应的值
                        .update();
            }
        }

        //6. 基于userId和昵称生成Token令牌
        String token = tokenService.createToken(
                Map.of(
                        "userId", member.getId(),
                        "nickName", member.getName()
        ));

        //7. 封装响应结果对象
        return LoginVo.builder().nickName(member.getName()).token(token).build();
    }

    /**
     * 绑定老人
     *
     * @param dto
     */
    @Override
    public void addMember(MemberUserAddDto dto) {
        //1.从ThreadLocal中获取操作人的family_member_id
        Long userId = UserThreadLocal.get();
        //2.根据dto查询老人信息
        Long elderId = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, dto.getIdCard())).getId();
        //判断老人身份是否已经绑定过
        FamilyMemberElder one = familyMemberElderService.lambdaQuery().eq(FamilyMemberElder::getElderId, elderId).eq(FamilyMemberElder::getFamilyMemberId, userId).one();
        if (one != null){
            throw new BaseException("老人信息已存在，请勿重复绑定！");
        }
        //3.封装数据
        FamilyMemberElder familyMemberElder = FamilyMemberElder.builder()
                .familyMemberId(Long.parseLong(userId.toString()))
                .elderId(elderId)
                .remark(dto.getRemark())
                .build();
        //4.存入family_member_elder表
        familyMemberElderService.save(familyMemberElder);
    }

    /**
     * 查询家人列表
     */
    @Override
    public List<FamilyMemberElderVo> selectMemberList() {
        //1.从ThreadLocal中获取操作人的family_member_id
        Long familyMemberId = UserThreadLocal.get();
        //2.获取绑定老人列表
        List<FamilyMemberElder> list = familyMemberElderService.list(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, familyMemberId));
        //3.封装数据
        if (CollUtil.isNotEmpty( list)){
            List<FamilyMemberElderVo> collect = list.stream().map(familyMemberElder -> {
                FamilyMemberElderVo familyMemberElderVo = BeanUtil.toBean(familyMemberElder, FamilyMemberElderVo.class);
                //获取每一个老人的elder_id，查询老人姓名
                Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getId, familyMemberElder.getElderId()));
                if (elder != null) {
                    familyMemberElderVo.setElderName(elder.getName());
                }
                return familyMemberElderVo;
            }).collect(Collectors.toList());
            return collect;
        }
        return Collections.emptyList();
    }

    /**
     * 查看家人列表（分页查询）
     *
     * @param pageNum
     * @param pageSize
     */
    @Override
    public List<PageListVo> selectMemberListByPage(Integer pageNum, Integer pageSize) {
        Long id =  UserThreadLocal.get();
        PageHelper.startPage(pageNum, pageSize);
        return familyMemberMapper.selectMemberListByPage(id);
    }

    /**
     * 查询健康数据
     *
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> QueryDevicePropertyStatus(DeviceDto dto) {

        HashMap<String, Object> stringListVOHashMap = new HashMap<>();
        // 根据设备名字查询设备id
        Device device = deviceService.lambdaQuery()
                .eq(StrUtil.isNotEmpty(dto.getDeviceName()), Device::getDeviceName, dto.getDeviceName())
                .eq(StrUtil.isNotEmpty(dto.getProductKey()), Device::getProductKey, dto.getProductKey())
                .one();
        // 查不到数据则返回空集合
        if (ObjectUtil.isEmpty(device)) {
            return Collections.emptyMap();
        }
        // 从缓存中获取最新数据
        String deviceDateList = (String) stringRedisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_DATA_LATEST, device.getIotId());
        // 缓存查不到数据返回空集合
        if (StrUtil.isBlank(deviceDateList)) {
            return Collections.emptyMap();
        }
        // 把Json字符串转成集合
        List<DeviceData> deviceDataList = JSONUtil.toList(deviceDateList, DeviceData.class);
        List<PropertyStatusInfoVO> propertyStatusInfoVOList = deviceDataList.stream().map((Function<DeviceData, PropertyStatusInfoVO>) deviceData -> {
            // 封装返回数据
            PropertyStatusInfoVO propertyStatusInfoVO = PropertyStatusInfoVO.builder()
                    .identifier(deviceData.getFunctionId())
                    .time(deviceData.getAlarmTime().atZone(ZoneId.of("Asia/Shanghai")).toInstant().toEpochMilli())
                    .value(deviceData.getDataValue())
                    .build();
            return propertyStatusInfoVO;
        }).collect(Collectors.toList());
        HashMap<String, Object> propertyStatusInfoVOMap = new HashMap<>();
        propertyStatusInfoVOMap.put("propertyStatusInfo", propertyStatusInfoVOList);
        // 封装数据返回
        stringListVOHashMap.put("list", propertyStatusInfoVOMap);
        return stringListVOHashMap;
    }
}
